/** @format */
const { User } = require("../model/index");
const { createToken } = require("../utils/jwt");

/**
 *
 * @param {Request} req
 * @param {Response} res
 */

module.exports.delUser = async (req, res, next) => {
  // const dbb = await User.findByIdAndRemove({ _id: req.query.id });
  const dbb = await User.findByIdAndUpdate(req.query.id, { isDel: true });
  if (dbb) {
    res.data = dbb;
    res.msg = "删除成功";
    res.status(200);
  } else {
    res.status(204);
  }
  next();
};
module.exports.getUser = async (req, res, next) => {
  const dbb = await User.find({
    $nor: [{ isDel: true }],
  });
  res.msg = "查找成功";
  (res.data = dbb), res.status(200);
  next();
};
module.exports.editUser = async (req, res, next) => {
  const dbb = await User.findByIdAndUpdate(req.body.id, req.body, {
    new: true,
  });
  res.msg = "修改成功";
  (res.data = dbb), res.status(201);
  next();
};

module.exports.regist = async (req, res, next) => {
  //   console.log(req.body);
  const userModel = new User(req.body);
  const dbback = await userModel.save();
  // console.log(dbback);
  res.msg = "新增用户成功";
  res.data = dbback;
  res.status(201);
  next();
};
module.exports.login = async (req, res, next) => {
  let dbback = await User.findOne(req.body);
  //   console.log(dbback);
  dbback = dbback.toJSON();
  dbback.token = await createToken(dbback);
  res.data = dbback;
  res.msg = "登录成功";
  res.status(201);
  next();
};
